<?php


namespace Question\Controller;

use Think\Controller;

/**
 * Class IndexController
 * @package Question\Controller
 * @郑钟良
 */
class IndexController extends Controller
{

    protected $mQuestionAnswerSupport;
    public function _initialize()
    {
        $this->mQuestionAnswerSupport=D('QuestionAnswerSupport');
        $recommendList=D('Question/QuestionRecommend')->getQuestions(20);
        $this->assign('recommendList',$recommendList);
        $this->setTitle('问题');
    }

    protected function needLogin(){
        if(!is_login()){
            $this->error('请先登录');
        }
        return true;
    }

    public function index($page = 1)
    {
        $aType = I('get.type', 0, 'intval');
        $aOrder = I('get.order', 'all', 'op_t');
        $aOrder = $aOrder == 'all' ? 'all' : ($aOrder == 'create_time' ? 'create_time' : 'answer_num');
        $this->assign('type', $aType);
        $this->assign('order', $aOrder);
        $typeList = D('Help/HelpType')->where(array('status' => 1))->field('id,title')->select();
        $this->assign('typeList', $typeList);
        if ($aOrder == 'all') {
            $aOrder = 'id';
        }
        if ($aType == 0) {
            $typeIds = array_column($typeList, 'id');
            $typeIds=array_merge($typeIds,array(0));
            $aType = array('in', $typeIds);
        }
        $questionList = D('Question/Question')->getList(array('type' => $aType,'is_repost'=>0), $totalCount, $page, $aOrder . ' desc');
        $this->assign('questionList', $questionList);
        $this->assign('totalCount', $totalCount);
        $this->setTitle('问题主页');
        $this->display();
    }

    public function detail(){
        $aId=I('get.id',0,'intval');
        if($aId==0){
            $this->error("参数错误！");
        }
        $question=D('Question/question')->getQuestion($aId);
        $this->assign('uid',$question['uid']);
        $this->assign('question',$question);
       // dump($question);exit;
        $this->assign('is_detail',1);
        $this->setTitle("问题详情页，{$question['title']}");
        $this->display();
    }

    public function share(){
        $aId=I('post.id',0,'intval');
        D('Question/question')->addFieldNum(array($aId),'share_num');
        S('question_'.$aId,null);
        $this->ajaxReturn(true);
    }

    public function getQuestion()
    {
        $aId = I('question_id', 0, 'intval');
        $question = D('Question/Question')->getQuestion($aId);
        $data['status'] = 0;
        if ($question) {
            $data['content'] = parse_popup($question['content']);
            $data['content_s'] = $question['content_s'];
            if($question['is_repost']){
                $data['other_content']=$question['other_content'];
                $data['title']=$question['original_question']['title'];
            }else{
                $data['other_content']='';
                $data['title']=$question['title'];
            }
            $data['status'] = 1;
        }
        $this->ajaxReturn($data);
    }

    public function repost()
    {
        $this->needLogin();
        $aQuestionId = $data['last_question_id'] = I('post.question_id', 0, 'intval');
        $aContent = $data['content'] = I('post.content', '', 'op_t');
        $aBeAnswer = I('post.beAnswer', '1', 'intval');
        $msg['status'] = 0;
        if (!$aQuestionId) {
            $msg['info'] = '参数传递错误！';
            $this->ajaxReturn($msg);
        }
        if (!$aContent) {
            $msg['info'] = '内容不能为空！';
            $this->ajaxReturn($msg);
        }
        if(mb_strlen($aContent,'utf-8')>400){
            $msg['info'] = '内容长度不能超过400！';
            $this->ajaxReturn($msg);
        }
        $fromQuestion = D('Question/Question')->getQuestion($data['last_question_id']);
        $data['type'] = $fromQuestion['type'];
        if ($fromQuestion['last_question_id'] == 0) {
            $data['first_question_id'] = $data['last_question_id'];
        } else {
            $data['first_question_id'] = $fromQuestion['first_question_id'];
        }
        $data['uid'] = is_login();

        $result = D('Question/QuestionRepost')->createQuestion($data);
        if ($result) {

            $msg['from_answer_num'] = $fromQuestion['answer_num'];
            if ($aBeAnswer) {
                $msg['from_answer_num']++;
            }
            if ($fromQuestion['is_repost'] == 0) {
                $ids = array($fromQuestion['id']);
            }else{
                $msg['from_repost_num'] = D('Question')->where(array('id'=>$fromQuestion['first_question_id']))->field('repost_num')->find();
                $msg['from_repost_num']=$msg['from_repost_num']['repost_num']++;
                $ids = array($fromQuestion['id'],$fromQuestion['first_question_id']);
            }

            $this->afterRepost($ids, $aBeAnswer,$aContent,$fromQuestion['uid']);
            $question = D('Question/Question')->getQuestion($result);
            $this->assign('question', $question);
            $msg['repost_num'] = $fromQuestion['repost_num'] + 1;
            $msg['have_old_repost'] = $fromQuestion['is_repost'] ? 1 : 0;
            $msg['first_question_id'] = $question['first_question_id'];
            $msg['question'] = $this->fetch('Public/_question');
            $msg['status'] = 1;
        } else {
            $msg['info'] = '存入数据库失败！';
        }
        $this->ajaxReturn($msg);
    }

    protected function  afterRepost($ids = array(), $aBeAnswer = 1,$aContent='',$to_uid=0)
    {
        $model=D('Question');
        $model->addFieldNum($ids,'repost_num');
        if ($aBeAnswer) {
            $data['question_id']=$ids[0];
            $data['uid']=is_login();
            $data['content']=$aContent;
            D('QuestionAnswer')->createAnswer($data);
            $userInfo=query_user(array('nickname'),is_login());
            sendMessage($to_uid,$userInfo['nickname'].'回答了你的问题','问题：您得到了新答案',U('question/index/detail',array('id'=>$ids[0])),is_login(),1);
            $model->addFieldNum(array($ids[0]),'answer_num');
        }
        return;
    }

    /**
     * 获取表情列表。
     */
    public function getSmile()
    {
        //这段代码不是测试代码，请勿删除
        exit(json_encode(D('Expression')->getAllExpression()));
    }

    public function loadAnswer(){
        $aQuestionId=I('post.question_id',0,'intval');
        $answerList=D('Question/QuestionAnswer')->getAnswerList(array('question_id'=>$aQuestionId),0,$totalCount,'create_time desc');
        $msg['content']='';
        foreach($answerList as $v){
            $this->assign('answer',$v);
            $msg['content']=$msg['content'].$this->fetch('Public/_answer');
        }
        unset($v);
        if(mb_strlen($msg['content'],'utf-8')>0){
            $msg['status']=1;
        }else{
            $msg['status']=0;
            $msg['info']='操作失败';
        }
        $this->ajaxReturn($msg);
    }

    public function loadFullAnswer(){
        $aAnswerId=I('post.answer_id',0,'intval');
        $answer=D('Question/QuestionAnswer')->getAnswerWithQuestion($aAnswerId);
        if($answer){
            $this->assign('answer',$answer);
            $msg['content']=$answer['content'];
            $msg['status']=1;
        }else{
            $msg['status']=0;
            $msg['info']='操作失败';
        }
        $this->ajaxReturn($msg);
    }

    public function postAnswer(){
        $this->needLogin();
        $aQuestionId=$data['question_id']=I('post.question_id',0,'intval');
        $aAnswerId=$data['to_answer_id']=I('post.answer_id',0,'intval');
        $aResponseId=$data['to_response_id']=I('post.response_id',0,'intval');
        $aContent=$data['content']=I('post.content','','op_t');
        $data['uid']=is_login();
        $msg['status']=0;
        if(!$aQuestionId){
            $msg['info']='参数错误';
            $this->ajaxReturn($msg);
        }
        if(mb_strlen($aContent,'utf-8')<4){
            $msg['info']='内容长度不能小于4';
            $this->ajaxReturn($msg);
        }
        $modelAnswer=D('QuestionAnswer');
        $model=D('Question');
        $result=$modelAnswer->createAnswer($data);
        if($result){
            $msg['status']=1;
            //回复数增加
            $ids=array($aQuestionId,$aAnswerId,$aResponseId);
            if($aAnswerId==0){
                $model->addFieldNum($ids,'answer_num');
                $msg['question_answer_num']=$model->where('id='.$aQuestionId)->getField('answer_num');
            }else{
                $modelAnswer->addFieldNum($ids,'answer_num');
                $msg['answer_num']=$modelAnswer->where('id='.$aAnswerId)->getField('answer_num');
            }
            //回复数增加 end
            //发消息
            send_question_answer_message($aQuestionId,$aAnswerId,$aResponseId,is_login());
            //发消息end
            $answer=$modelAnswer->getAnswer($result);
            $this->assign('answer',$answer);
            $msg['answer']=$answer;
            $msg['answerHtml']=$this->fetch('Public/_answer');
        }else{
            $msg['status']=0;
            $msg['info']='操作失败';
        }
        $this->ajaxReturn($msg);
    }

    public function supportAnswer(){
        $this->needLogin();
        $aAnswerId=I('post.answer_id',0,'intval');
        $aType=I('post.type',0,'intval');
        $msg['status']=0;
        if($aAnswerId==0){
            $msg['info']='参数错误';
            $this->ajaxReturn($msg);
        }
        if(!answer_can_support($aAnswerId)){
            $msg['info']='重复操作';
            $this->ajaxReturn($msg);
        }
        $data['uid']=is_login();
        $data['answer_id']=$aAnswerId;
        $data['type']=$aType;
        $data['create_time']=time();
        $result=$this->mQuestionAnswerSupport->add($data);
        if($result){
            $field=$aType?'support':'oppose';//0:支持，1:反对
            $modelAnswer=D('QuestionAnswer');
            $modelAnswer->addFieldNum(array($aAnswerId),$field);
            $answer=$modelAnswer->where('id='.$aAnswerId)->find();
            $this->assign('answer',$answer);
            $msg['html']=$this->fetch('Public/_support');
            $msg['status']=1;
        }else{
            $msg['info']='操作失败';
        }
        $this->ajaxReturn($msg);
    }
}